package mysql

import (
	"crypto/md5"
	"database/sql"
	"encoding/hex"
	"web-app/models"
)

var secret string = "Hello Andy"

func CheckUserExist(username string) (err error) {
	sqlstr := `select count(user_id) from user where username =?`
	var count int
	if err := db.Get(&count, sqlstr, username); err != nil {
		return err
	}
	if count > 0 {
		return ErrorUserExist
	} else {
		return nil
	}

}

func GetUserByID(id int64) (username string, err error) {
    sqlstr := `select username from user where user_id = ?`  // 只查询username
    err = db.Get(&username, sqlstr, id)
    return username, err
}

// 向数据库中插入一条新的用户记录
func InsertUser(user *models.User) (err error) {
	//对密码进行加密
	password := encryptPassword(user.Password)
	//执行SQL语句入库
	sqlstr := `insert into user(user_id,username,password) values(?,?,?)`
	_, err = db.Exec(sqlstr, user.UserID, user.Username, password)
	return
}

func encryptPassword(oPassword string) string {
	h := md5.New()
	h.Write([]byte(secret))
	return hex.EncodeToString(h.Sum([]byte(oPassword)))
}

func Login(p *models.User) (err error) {
	oPassword := p.Password
	sqlStr := `select user_id,username,password from user where username =?`
	err = db.Get(p, sqlStr, p.Username)
	if err == sql.ErrNoRows {
		return ErrorUserNotExist
	}
	if err != nil {
		//查询数据库失败
		return err
	}
	password := encryptPassword(oPassword)
	if password != p.Password {
		return ErrorInvalidPassword
	}
	return
}
